package com.barkerton.crawler.queuing;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import com.barkerton.crawler.Seed;

/**
 * Queue of URLs to crawl.
 * 
 * @author c.barker
 *
 */
public class CrawlerQueue implements Queue<Seed> {

	private static final CrawlerQueue SINGLETON = new CrawlerQueue();
	private static final BlockingQueue<Seed> QUEUE = 
		new LinkedBlockingQueue<Seed>(QUEUE_CAPACITY);
	
	// private constructor requires call to getInstance
	private CrawlerQueue() { }
	
	/**
	 * @return	SINGLETON object
	 */
	public static CrawlerQueue getInstance() {
		return SINGLETON;
	}
	
	/**
	 * @return Current size of the queue
	 */
	public int size() {
		return QUEUE.size();
	}
	
	/**
	 * Removes every element in the entire queue
	 */
	public void clear() {
		QUEUE.clear();
	}
	
	/**
	 * Blocks until the object can be added.
	 * Does not add Seed if it already exists in the queue.
	 * 
	 * @param Seed object to be added to the queue
	 */
	public void enqueue(Seed url) throws InterruptedException {
		if (!QUEUE.contains(url))
			QUEUE.put(url);
	}
	
	/**
	 * Blocks until an item is available to remove
	 * @return Seed item from the queue
	 */
	public Seed dequeue() throws InterruptedException {
		return QUEUE.take();
	}
	
	public Seed peek() {
		return QUEUE.peek();
	}
}
